//菜单树
angular.module('app').component('mPageTree', {
    templateUrl: getTemplateUrl('matrix/component/tpl/mPageTree.html'),
    bindings: {
        sys: '@',
        reqId: '@',
        menu:"<",
        pageId:'@',
        onPageSelect: '&'
    },
    controller: function ($scope, $element, $http, $attrs, $modal, $timeout, $rootScope) {
        var ctrl = this;
        ctrl.my_tree = {};
        ctrl.isPage = true;
        ctrl.isInput = false;
        ctrl.selectedBranch = null;
        ctrl.my_tree_handler = function (branch) {
            console.log(branch);
            ctrl.selectedBranch = ctrl.my_tree.get_selected_branch();
            ctrl.onPageSelect({
                info: branch
            });
            ctrl.isPage = branch.pageType == "page" ? true : false;
            if(branch.attrs != undefined) {
                ctrl.isInput = branch.componentId == "Input" ? true : false;
            } else {
                ctrl.isInput = false;
            }

        };
        ctrl.load = function () {
             var url = matrix_product_url + '/page/getMenuPages?menuId='+ctrl.menu.id;
            $.ajax({
                type: "get",
                url: url,
                dataType: "JSON",
                async: false,
                success: function (data) {
                    ctrl.my_data = data.data;
                    if(data.data != null) {
                        angular.forEach(ctrl.my_data, function(menuPage){
                            menuPage.pageLevel=1;
                            menuPage.pageType='page';
                              $http.get(matrix_product_url+'/page/getPageElements?pageId='+menuPage.id).success(function(data){
                                menuPage.children=data.data;
                            })
                        })
                        if(ctrl.my_data.length>0){
                            $timeout(function () {
                                if (ctrl.selectedBranch != null) {
                                    ctrl.my_tree.set_select_branch_by_id(ctrl.selectedBranch.asParentId);
                                } else {
                                    ctrl.my_tree.set_select_branch_by_id(ctrl.my_data[0].asParentId);
                                }
                                return ctrl.my_tree.expand_all();
                            }, 500);
                        }
                    }
                },
                complete: function (xhr, status) {
                }
            });
        }

        ctrl.load();

        ctrl.updatePop = function (info, pageType, componentType, saveFun) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'pageUpdatePop.html',
                controller: 'pageUpdatePopCtrl',
                keyboard: false,
                backdrop: 'static',
                resolve: {
                    info: function () {
                        return info;
                    },
                    type: function() {
                        return pageType;
                    },
                    componentType:function(){
                        return componentType;
                    }
                }
            });

            modalInstance.result.then(function (result) {
                    ctrl.load();
                },
                function (reason) {
                    //保存信息
                    saveFun(reason)
                });
        }
        ctrl.dataFun = function (info, treeIcon, visible) {
            var obj = {}
            if (info.parent_id == '0') {
                info.level = '0';
            }
            obj.branch = info;
            if(info.childs!=undefined){
               info.children=info.childs;
            }
            obj.classes = info.classes;
            obj.tree_icon = treeIcon;
            obj.visible = visible;
            obj.status = info.status;
            if(info.title == undefined){
                 obj.label = info.componentId;
            }else{
                 obj.label = info.title;
            }
            if(info.pageLevel==undefined){
                obj.level = info.index+1;
            }else{
                obj.level = info.pageLevel;
            }
            return obj;
        }

        ctrl.addPage=function(){
            var info={}
            var pageType = "page"
            info.fileName = "";
            info.menuId   = ctrl.menu.id;
            info.menuPath = ctrl.menu.menu_data.routeId;
            info.title    = "";
            info.type     = 'add';
            ctrl.updatePop(info, pageType, null, function (data) {
                //data.path=data.path+"/"+data.fileName;
                data.menuPath = ctrl.menu.menu_data.routeId;
                savePage(data);
            });
        }


        ctrl.updateBranch = function () {
            var info = {};
            var pageType = "page"
            info.fileName = ctrl.selectedBranch.fileName;
            info.menuId   = ctrl.selectedBranch.menuId;
            info.menuPath = ctrl.selectedBranch.menuPath;
            info.title    = ctrl.selectedBranch.title;
            info.id       = ctrl.selectedBranch.id;
            ctrl.updatePop(info,pageType, null,function (data) {
               
                savePage(data);
            });
        }

        //新增元素
        ctrl.addPageElement = function () {
            var info = {};
            info.pageId=ctrl.selectedBranch.id;
            if(ctrl.selectedBranch.pageLevel==undefined){
                info.parentId=ctrl.selectedBranch.id;
            }else{
                info.parentId=0;
            }
            var pageType="pageElement"
            ctrl.updatePop(info,pageType,ctrl.selectedBranch.componentId, function (res) {
                $http.get(sys_config_url+'/component/getAvailableSubElementByElement?component_type='+res.componentId).success(function(data){
                    if(data.code == "0"){
                        var result = {};
                        result.attrs = {"name": data.data.attrs[0].name, "prototype": data.data.attrs[0].prototype, "value": data.data.attrs[0].value};
                        result.componentId = res.componentId;
                        if(ctrl.selectedBranch.pageType == "page") {
                            result.index = ctrl.selectedBranch.pageLevel + 1;
                            result.pageId = ctrl.selectedBranch.id;
                            result.parentId = 0;
                        } else {
                            result.index = 1000;
                            result.pageId = ctrl.selectedBranch.pageId;
                            result.parentId = ctrl.selectedBranch.id;
                        }
                        savePageElement(result);
                    }else{
                        $rootScope.showMessage('error', '失败！', data.desc);
                    }
                })
            });
        }

        //删除页面
        ctrl.delete=function(){
            var info = {};
            var title="";
            var url="";
            if(ctrl.selectedBranch.pageType==undefined || ctrl.selectedBranch.pageType==null || ctrl.selectedBranch.pageType==""){
                url=matrix_product_url+'/page/deletePageElement?elementId='+ctrl.selectedBranch.id;
                title=ctrl.selectedBranch.componentId
            }else{
                url=matrix_product_url+'/page/deletePage?pageId='+ctrl.selectedBranch.id;
                title=ctrl.selectedBranch.title;
            }
            info.titleData = "提示";
            info.bodyData = "确定要删除'" + title + "'吗？";
            $rootScope.confirmWindow(info, function (data) {
                if(data){
                      $http.get(url).success(function(data){
                            if(data.code=="0"){
                                ctrl.load();
                                $rootScope.showMessage('success', '成功！', '删除数据成功！');
                            }else{
                                $rootScope.showMessage('error', '失败！', data.desc);
                            }
                        })
                }
            })
        }

        //刷新页面
        ctrl.applyPageConfig=function(){
            $http.get(matrix_product_url+"/page/applyPageConfig?pageId="+ctrl.selectedBranch.id).success(function(data){
                if(data.code == "0"){
                    $rootScope.showMessage('success', '成功！', '刷新Tom成功！');
                }else{
                    $rootScope.showMessage('error', '失败！', data.desc);
                }
            })
        }

        function reloadApplyPage() {
            var url = matrix_product_url+"/page/applyPageConfig?pageId="+ctrl.selectedBranch.pageId;
            $http.get(url).success(function(data){
                if(data.code=='0'){
                    $rootScope.showMessage('success', '成功！', 'Tom更新成功！');
                }else{
                    $rootScope.showMessage('error', '失败！', data.desc);
                }
            })
        }

        function savePage(page) {
            $.ajax({
                type:'post',
                url:matrix_product_url+'/page/savePage',
                data:JSON.stringify(page),
                contentType: "application/json; charset=utf-8",
                success:function(data){
                    if (data.code == "0") {
                        ctrl.load();
                        //reloadApplyPage();
                    } else {
                        $rootScope.showMessage('error', '失败！', data.desc);
                    }
                }
            })
        }

        function savePageElement(data){
             $.ajax({
                type:'post',
                url:matrix_product_url+'/page/createPageElement',
                data:JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                success:function(data){
                    if (data.code == "0") {
                        ctrl.load();
                        //reloadApplyPage();
                        $rootScope.showMessage('success', '成功！', '创建成功！');
                    } else {
                        $rootScope.showMessage('error', '失败！', data.desc);
                    }
                }
            })
        }

    }
});
app.controller("pageUpdatePopCtrl", ["$scope", "$rootScope", '$modalInstance', 'info','type','$http','componentType', function ($scope, $rootScope, $modalInstance, info,type,$http,componentType) {
    $scope.info = info;
    $scope.type=type;
    $scope.ElementByElement={}
    $scope.componentType=componentType;

    if($scope.type=='pageElement'){
        if($scope.componentType==undefined){
            $scope.componentType="ROOT";
        }
        $.ajax({
                type: "get",
                url: sys_config_url+'/component/getAvailableSubElementByElement?component_type='+$scope.componentType,
                dataType: "JSON",
                async: false,
                success: function (data) {
                    if(data.code == "0"){
                        $scope.ElementByElement=data.data.available_sub_component;
                    }else{
                        $rootScope.showMessage('error', '失败！', data.desc);
                    }
                }
            });
    }

    $scope.buttonsClick = function (type) {
        if (type == 'cancel') {
            $modalInstance.close('cancel');
        } else {
            $modalInstance.dismiss($scope.info);
        }
    }
}]);